package com.thanhloyal.exchanger.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.json.simple.JSONArray;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

import com.thanhloyal.exchanger.Currency;
import com.thanhloyal.exchanger.RateDataItem;

import android.content.Context;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

public class Utils {
	
	private Context mContext;
	
	
	
	public Utils(Context mContext) {
		super();
		this.mContext = mContext;
	}


	public String readTextFile(Context ctx,String fileName){
		String content;
		AssetManager mgr = mContext.getAssets();
		String line;
		StringBuffer stringBuffer = new StringBuffer("");
		try {
			InputStream is = mgr.open(fileName);
			InputStreamReader isr = new InputStreamReader(is);
			BufferedReader br = new BufferedReader(isr);
			while((line = br.readLine()) != null){
				stringBuffer.append(line);
			}
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		content = stringBuffer.toString();
		return content;
	}
	
	
	/* 
	 * Steps to build a currency:
	 * 1. Get full name
	 * 2. Get flag image
	 * 3. Push back currency code name in UPPER CASE
	 * */
	public Currency buildCurrencyFormCode(String code){
		String name = "";
		Bitmap flag = null;
		// Because names are in lower case
		// we make sure that we will use lower case to find the string
		code = code.toLowerCase();
		
		// "try" is special
		if (code.equalsIgnoreCase("try")) {
			code = "_try";
		}
		Resources res = mContext.getResources();
		AssetManager assetMgr = mContext.getAssets();
		
		Currency c = new Currency();
		
		// Get its name
		String pkName = mContext.getPackageName();
		int stringResId = res.getIdentifier(code, "string", pkName);
		if(stringResId == 0){
			Log.v("Loyal", "buildCurrencyFormCode(): Currency name not found for " + code);
			return null;
		} else {
			name = mContext.getString(stringResId);
			//Log.v("Loyal", name);
			c.setCurrencyName(name);
		}
		
		// Get the flag bitmap
		String flagFileName = "flags/flag_"+code+".png";   // example: flags/flag_usd.png
		try {
			flag = BitmapFactory.decodeStream(assetMgr.open(flagFileName));
			c.setFlag(flag);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			// e.printStackTrace();
			Log.v("Loyal", "buildCurrencyFormCode(): No flag for "+code.toUpperCase()+" found.("
			+ name + ")");
			return null;
		}
		
		
		// Push back Upper-case code name
		code = code.toUpperCase();
		c.setCurrencyCode(code);
		
		// Log.v("Loyal", c.getCurrencyCode()+ " " + c.getCurrencyName() + " "+ c.getFlag().getByteCount()/1024 +" kB");
		return c;
	}

	
	public ArrayList<RateDataItem> getRatesData(){
		String RATES_FOLDER = "rates";
		String ASK_RATE_FILE_NAME = RATES_FOLDER + "/askRates.txt";
		String BID_RATE_FILE_NAME = RATES_FOLDER + "/bidRates.txt";
		String PAIRS_FILE_NAME = RATES_FOLDER + "/pairs.txt";
		
		SchemaHelper schemaHelper = new SchemaHelper(this.mContext);
		ArrayList<RateDataItem> rates = schemaHelper.getAllRatesData();
		
		// There is no data in the database.
		// Read from asset files.
		if(rates.size() == 0){
			// TODO: do this
			AssetManager mgr = mContext.getAssets();
			JSONParser parser = new JSONParser();
			try {
				JSONArray askRatesArray = (JSONArray) parser.parse(new InputStreamReader(mgr.open(ASK_RATE_FILE_NAME)));
				JSONArray bidRatesArray = (JSONArray) parser.parse(new InputStreamReader(mgr.open(BID_RATE_FILE_NAME)));
				JSONArray pairsArray = (JSONArray) parser.parse(new InputStreamReader(mgr.open(PAIRS_FILE_NAME)));
				
				for (int i = 0; i < pairsArray.size(); i++) {
					RateDataItem rdi = new RateDataItem((String)pairsArray.get(i),
							Double.parseDouble(askRatesArray.get(i).toString()), 
							Double.parseDouble(bidRatesArray.get(i).toString()) );
					rates.add(rdi);
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} 
		return rates;
	}
	
	
}
